package com.hongdee.base.sendMsg.service.impl;

import com.hongdee.base.sendMsg.dao.ISendMsgDao;
import com.hongdee.base.sendMsg.entity.SendMessage;
import com.hongdee.base.sendMsg.service.ISendMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SendMsgServiceImpl implements ISendMsgService{

    @Autowired
    private ISendMsgDao iSendMsgDao;

    /**
     * 一个内容发送多个人
     * @param content
     * @param mobiles
     * @param extno
     * @return
     */
    @Override
    public String sendGet(String content,List<String> mobiles,String extno){

        String addr = "http://101.201.196.153:8088/qfsms/sendsms";
        String uId = "runhuakx";
        String pwd = this.getMd5("runhua321");

        //分写电话号码
        StringBuffer mobile = new StringBuffer();
        for(String m:mobiles){
            if(m.length()!=11){//电话号码不等于11位的跳过
                continue;
            }
            mobile.append(m+",");
        }
        if(mobile.length()>0){
            mobile.replace(mobile.length()-1,mobile.length(),"");
        }
        //短信格式
        StringBuffer msgCon = new StringBuffer();
        msgCon.append("【润华集团】"+content+",退订回N");

        StringBuffer resultBuffer = null;
        // 构建请求参数
        BufferedReader br = null;
        try{
            //短信内容转编码格式
            String msgContent = URLEncoder.encode(msgCon.toString(),"GBK");
            String address = addr+"?user="+uId+"&pwd="+pwd+"&mobile="+mobile+"&msg="+msgContent+"&extno="+extno;
            System.out.println(address);
            URL url = new URL(address);
            URLConnection con = url.openConnection();
            // 设置请求属性
            con.setRequestProperty("accept", "*/*");
            con.setRequestProperty("connection", "Keep-Alive");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("contentType", "GBK");
            con.setRequestProperty("Accept-Charset", "GBK");
            con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立连接
            con.connect();
            resultBuffer = new StringBuffer();
            br = new BufferedReader(new InputStreamReader(con.getInputStream(), "GBK"));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
            //保存记录
            this.saveGetMessage(addr,uId,pwd,mobiles,resultBuffer.toString(),msgCon.toString(),extno);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }

    /**
     * 保存发送短信的记录
     * @param url
     * @param uid
     * @param pwd
     * @param mobiles
     * @param result
     * @throws Exception
     */
    private void saveGetMessage(String url,String uid,String pwd,List<String> mobiles,String result,String content,String extno) throws Exception{

        for (String moible:mobiles){
            SendMessage sendMessage = new SendMessage();
            sendMessage.setUrl(url);
            sendMessage.setPwd(pwd);
            sendMessage.setUid(uid);
            sendMessage.setResult(result);
            sendMessage.setMobile(moible);
            sendMessage.setContent(content);
            sendMessage.setExtno(extno);
            sendMessage.setCreateTime(System.currentTimeMillis());
            this.iSendMsgDao.saveOrUpdate(sendMessage);
        }
    }

    /**
     * 多个内容发送多个人
     * @param list
     * @param extno
     * @return
     */
    @Override
    public String sendPost(List<Map<String,Object>> list, String extno){

        String addr = "http://101.201.196.153:8088/qfsms/sendsms";
        String uId = "runhua";
        String pwd = this.getMd5("runhua321");
        StringBuffer resultBuffer = null;
        // 构建请求参数
        BufferedReader br = null;
        try{
            for(Map<String,Object> map :list){

                //分写电话号码
                String mobile = new String();
                mobile = map.get("mobile").toString();
                if(mobile.length()!=11){//电话号码不等于11位的跳过
                    continue;
                }
                //短信格式
                StringBuffer msgCon = new StringBuffer();
                msgCon.append("【润华集团】"+map.get("content")+",退订回N");
                //短信内容转编码格式
                String msgContent = URLEncoder.encode(msgCon.toString(),"GBK");
                String address = addr+"?user="+uId+"&pwd="+pwd+"&mobile="+mobile+"&msg="+msgContent+"&extno="+extno;
                System.out.println(address);
                URL url = new URL(address);
                URLConnection con = url.openConnection();
                // 设置请求属性
                con.setRequestProperty("accept", "*/*");
                con.setRequestProperty("connection", "Keep-Alive");
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                con.setRequestProperty("contentType", "GBK");
                con.setRequestProperty("Accept-Charset", "GBK");
                con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立连接
                con.connect();
                resultBuffer = new StringBuffer();
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), "GBK"));
                String temp;
                while ((temp = br.readLine()) != null) {
                    resultBuffer.append(temp);
                }

                //保存记录
                this.savePostMessage(addr,uId,pwd,mobile,msgCon.toString(),extno,resultBuffer.toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }

    /**
     * 保存短信内容
     * @param url
     * @param uid
     * @param pwd
     * @param extno
     * @throws Exception
     */
    private void savePostMessage(String url,String uid,String pwd,String mobile,String content,String extno,String result) throws Exception{

            SendMessage sendMessage = new SendMessage();
            sendMessage.setUrl(url);
            sendMessage.setPwd(pwd);
            sendMessage.setUid(uid);
            sendMessage.setResult(result);
            sendMessage.setMobile(mobile);
            sendMessage.setContent(content);
            sendMessage.setExtno(extno);
            sendMessage.setCreateTime(System.currentTimeMillis());
            this.iSendMsgDao.saveOrUpdate(sendMessage);
    }
    /**
     * 给密码加密
     * @param pwd
     * @return
     */
    private String getMd5(String pwd){

        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update((pwd).getBytes("UTF-8"));
            byte b[] = md5.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for(int offset=0; offset<b.length; offset++){
                i = b[offset];
                if(i<0){
                    i+=256;
                }
                if(i<16){
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }

            pwd = buf.toString();
            System.out.println("result = " + pwd);

        }catch (Exception e){
            e.printStackTrace();
        }
        return pwd;
    }
}
